package com.quktzhuanka.app.adapter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Html;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.lljjcoder.style.citylist.Toast.ToastUtils;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.quktzhuanka.app.CaiNiaoApplication;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.activity.NewShareActivity;
import com.quktzhuanka.app.activity.PromotionDetailsActivity;
import com.quktzhuanka.app.activity.TaskBigImgActivity;
import com.quktzhuanka.app.bean.BkBean;
import com.quktzhuanka.app.bean.PromotionDetailsBean;
import com.quktzhuanka.app.bean.Response;
import com.quktzhuanka.app.common.SPUtils;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.https.onOKJsonHttpResponseHandler;
import com.quktzhuanka.app.utils.BitmapUtils;
import com.quktzhuanka.app.utils.ImgUtils;
import com.quktzhuanka.app.utils.RelativeDateFormat;
import com.quktzhuanka.app.utils.StringUtils;
import com.quktzhuanka.app.utils.ZxingUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;


import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class BkAdapter extends CommonAdapter<BkBean.BKItem> {

    PromotionDetailsBean data;

    DecimalFormat df=new DecimalFormat("0.00");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:m:s");

    public BkAdapter(Context context, int layoutId, List<BkBean.BKItem> datas) {
        super(context, layoutId, datas);
    }

    @Override
    protected void convert(final ViewHolder viewHolder, final BkBean.BKItem item, final int position) {
        //设置标题
        TextView title = viewHolder.getView(R.id.txt_content);
        title.setText(Html.fromHtml(item.goods_name == null ? "" : item.goods_name));
        Glide.with(mContext).load(R.mipmap.app_icon).dontAnimate().into((ImageView) viewHolder.getView(R.id.img_head));
        viewHolder.setText(R.id.txt_nickname, "赚咖联盟");
//        final FrameLayout shareFl =  viewHolder.getView(R.id.share_fl);
//        final ImageView erweima_tv =  viewHolder.getView(R.id.erweima_tv);
        Date date = null;
        try {
            date = format.parse(item.create_time);
            viewHolder.setText(R.id.txt_time, RelativeDateFormat.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
            viewHolder.setText(R.id.txt_time, item.create_time);
        }

        viewHolder.setText(R.id.txt_share_num, item.volume);
        try {
            viewHolder.setText(R.id.txt_high_yj, "最高奖:￥" + (String.format("%.2f", (StringUtils.doStringToDouble(item.zk_final_price) - StringUtils.doStringToDouble(item.coupon_amount)) * ((float) SPUtils.getIntData(mContext, "rate", 50) / 100) * Double.valueOf(item.commission_rate) / 100)).replace(".00", ""));
        } catch (NumberFormatException e) {
            viewHolder.setText(R.id.txt_high_yj, "最高奖:￥" + (String.format("%.2f", StringUtils.doStringToDouble(item.zk_final_price) * ((float) SPUtils.getIntData(mContext, "rate", 50) / 100) * Double.valueOf(item.commission_rate) / 100)).replace(".00", ""));
        }
        viewHolder.getView(R.id.txt_coupon_amount).setVisibility(View.GONE);
//        viewHolder.setText(R.id.txt_coupon_amount, "优惠券:￥" + item.coupon_amount+"      券后:￥"+df.format(Double.valueOf(item.zk_final_price==null?"0":item.zk_final_price)-Double.valueOf(item.coupon_amount==null?"0":item.coupon_amount)));
        viewHolder.setText(R.id.txt_desc, item.description);
        GridView gridView = viewHolder.getView(R.id.item_grid);
        final List<String> list = new ArrayList<>();
        viewHolder.getView(R.id.txt_copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", item.description);
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtils.showShortToast(mContext, "复制成功");
            }
        });
        if (item.small_images != null) {
            list.addAll(item.small_images);
        } else {
            list.add(item.pict_url);
        }
        gridView.setLayoutParams(new LinearLayout.LayoutParams(BitmapUtils.getScreenWith(mContext) * 2 / 3, ViewGroup.LayoutParams.WRAP_CONTENT));
        GridVIewAdapter adapter = new GridVIewAdapter(mContext, R.layout.shequ_item_grid, list.size() > 4 ? list.subList(0, 4) : list, 0);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<String> recordPaths = new ArrayList<>(); //缺陷记录的图片集合
                for (int i = 0; i < list.size(); i++) {
                    recordPaths.add(list.get(i));
                }
                Intent imgIntent = new Intent(mContext, TaskBigImgActivity.class);
                imgIntent.putStringArrayListExtra("paths", recordPaths);
                imgIntent.putExtra("title", "图片");
                imgIntent.putExtra("position", position);
                mContext.startActivity(imgIntent);
            }
        });
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("num_iid", item.goods_id);
                Intent intent = new Intent(mContext, PromotionDetailsActivity.class);
                intent.putExtras(bundle);
                mContext.startActivity(intent);
//                RequestParams requestParams = new RequestParams();
//                requestParams.put("id", item.goods_id);
//                HttpUtils.post(Constants.UPDATE_SHARE_NUM, requestParams, new TextHttpResponseHandler() {
//                    @Override
//                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                    }
//                    @Override
//                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
////                        getDatas().get(position).setShare_num((Integer.valueOf( getDatas().get(position).getShare_num())+1)+"");
////                        notifyDataSetChanged();
//                    }
//                });
            }
        });
        viewHolder.getView(R.id.txt_share_num).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//               MessageEvent messageEvent=new MessageEvent("share2");
//               messageEvent.setPosition(position);
//               EventBus.getDefault().post(messageEvent);
                final RequestParams requestParams1 = new RequestParams();
                requestParams1.put("num_iid", item.goods_id);
                HttpUtils.post(Constants.HOME_TBK_GETGOODSMSG_URL, requestParams1, new onOKJsonHttpResponseHandler<PromotionDetailsBean>(new TypeToken<Response<PromotionDetailsBean>>() {
                }) {
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Response<PromotionDetailsBean> datas) {
                        if (datas.isSuccess()) {
                            data = datas.getData();
                            if (data != null) {

                                String spUrl = "";
                                if (data.getCoupon_click_url_r() == null || "".equals(data.getCoupon_click_url_r())) {
                                    spUrl = data.getCoupon_click_url();
                                } else {
                                    spUrl = data.getCoupon_click_url_r();
                                }
                                try {
                                    viewHolder.setText(R.id.after_coupon_share_tv,"￥" + (String.format("%.2f", StringUtils.doStringToDouble(data.getZk_final_price()) - StringUtils.doStringToDouble(data.getCoupon_amount()))) + "元");
                                } catch (NumberFormatException e) {
                                    viewHolder.setText(R.id.after_coupon_share_tv,"￥" + (String.format("%.2f", StringUtils.doStringToDouble(data.getZk_final_price()))) + "元");
                                }
                                viewHolder.setText(R.id.price_share_tv,"原价￥" + data.getZk_final_price());
                                viewHolder.setText(R.id.tv_for_share,data.getCoupon_amount()+"元券");
                                //  分享图片二维码
//                                if("Y".equals(CaiNiaoApplication.getUserInfoBean().user_msg.is_share_vip)){
//                                    erweima_tv.setImageBitmap(ZxingUtils.createBitmap(SPUtils.getStringData(mContext,"share_url_vip","")+ "/wap.php/Index/share/num_iid/" + data.getNum_iid() + "/uid/" + SPUtils.getStringData(mContext, Constants.UID, "")));
//                                }else{
//                                    erweima_tv.setImageBitmap(ZxingUtils.createBitmap(Constants.SHARE_URL + "/wap.php/Index/share/num_iid/" + data.getNum_iid() + "/uid/" + SPUtils.getStringData(mContext, Constants.UID, "")));
//                                }

                                // 获得淘口令
                                RequestParams requestParams = new RequestParams();
                                requestParams.put("text", item.goods_name);
                                requestParams.put("url", spUrl);
                                requestParams.put("logo", data.getPict_url());
                                HttpUtils.post(Constants.CREATE_TP_WD, requestParams, new TextHttpResponseHandler() {
                                    @Override
                                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                    }

                                    @Override
                                    public void onStart() {
                                        super.onStart();
                                    }

                                    @Override
                                    public void onFinish() {
                                        super.onFinish();
                                    }

                                    @Override
                                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(responseString);
                                            int code = jsonObject.optInt("code");
                                            String msg = jsonObject.optString("msg");
                                            if (code == 0) {
                                                String spTkl = jsonObject.optString("data");

                                                //  分享
                                                Bundle bundle = new Bundle();
                                                ArrayList<String> images = new ArrayList<>();
                                                if (list != null) {
                                                    for (int i = 0; i < list.size(); i++) {
                                                        images.add(list.get(i));
                                                    }
                                                }
                                                String after_price = String.format("%.2f", StringUtils.doStringToDouble(item.zk_final_price) - StringUtils.doStringToDouble(item.coupon_amount));
                                                bundle.putStringArrayList("urls", images);
                                                Intent intent = new Intent(mContext, NewShareActivity.class);
                                                intent.putExtra("shouyi", data.getCommission());
                                                intent.putExtra("name", item.goods_name);
                                                intent.putExtra("price", item.zk_final_price);
                                                intent.putExtra("after_price", after_price);
                                                intent.putExtra("kouling", spTkl);
                                                 intent.putExtra("link", "");
                                                intent.putExtra("bitmap", bundle);

//                                                Bitmap bit = BitmapUtils.createViewBitmap(shareFl, mContext);
//                                                String url = System.currentTimeMillis() + ".jpg";
//                                                boolean is = ImgUtils.saveImageToGallery2(mContext, bit, url);
//                                                if (is) {
//                                                    intent.putExtra("imgurl", url);
//                                                } else {
//                                                    return;
//                                                }
                                                mContext.startActivity(intent);
                                            }

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                            }
                        }
                    }
                });

            }

        });
    }
    }
